package fun.aiwith.learn.peacock.controller;

import fun.aiwith.learn.peacock.entity.User;
import fun.aiwith.learn.peacock.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: tongqianwen
 * @Date: 2025/7/23
 */
@Slf4j
@Controller
@RequestMapping("/user")
@SessionAttributes("user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@ModelAttribute User user, Model model) {
        // 这里可以添加用户注册逻辑，比如保存用户到数据库
        log.info("Registering user: {}", user);
        model.addAttribute("user", user);
        userRepository.save(user);
        model.addAttribute("message", "Registration successful! Welcome, " + user.getUsername() + "!");
        return "registrationSuccess";
    }

    @GetMapping("/login")
    public String showLoginForm(Model model) {
        model.addAttribute("user", new User());
        return "login";
    }

    // 处理登录请求
    @PostMapping("/login")
    public String loginUser(@ModelAttribute User user, Model model) {
        // 模拟登录验证逻辑
        log.info("Attempting to log in user: {}", user);
        User data = userRepository.findByUsername(user.getUsername())
                .orElse(null);
        log.info("found user: {}", data);

        boolean isValid = data != null &&
                          StringUtils.hasText(data.getUsername()) &&
                          data.getPassword().equals(user.getPassword());

        if (isValid) {
            model.addAttribute("message", "登录成功！欢迎 " + user.getUsername());
            return "loginSuccess";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }
}
